package com.van.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.van.dao.ProductDao;
import com.van.dao.TagDao;
import com.van.pojo.Product;
import com.van.util.MybatisUtil;


/**
 * Servlet implementation class ProductOperationServlet
 */
@WebServlet("/productOperation")
public class ProductOperationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProductOperationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Product product = new Product();
		TagDao tagdao = MybatisUtil.getSession().getMapper(TagDao.class);
		product.setCode(request.getParameter("code"));
		product.setNote(request.getParameter("note"));
		product.setPrice(Integer.valueOf(request.getParameter("price")));
		product.setTag(tagdao.selectById(Integer.valueOf(request.getParameter("tag_id"))));
		product.setTitle(request.getParameter("title"));
		product.setTotalNumber(Integer.valueOf(request.getParameter("totalNumber")));
		SqlSession session = MybatisUtil.getSession();
		ProductDao productdao = session.getMapper(ProductDao.class);
		productdao.insertProduct(product);
		session.commit();
		System.out.println(product);
		response.sendRedirect("product");
	}

}
